package com.jungle.base.interceptor;

import com.jungle.common.core.domain.model.LoginUser;
import com.jungle.common.helper.LoginHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Connection;


@Slf4j
//@Component
//@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class MybatisPermissionInterceptor /*implements Interceptor*/ {

//    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        log.info("这里是 mybatis sql拦截器");

        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        String sql = boundSql.getSql();//获取到原始sql语句

        if (sql.contains("from yj_yjsjb")) {
            LoginUser loginUser;
            try {
                loginUser = LoginHelper.getLoginUser();
            } catch (NullPointerException e) {
                log.warn(e.getMessage());
                return sql;
            }
            Long userId = loginUser.getUserId();
            String xzqhbm = loginUser.getAreaCode();
            if (sql.contains("where")) {
                sql = sql.substring(0, sql.indexOf("where") + "where".length()) +
                    " yzqhbm like '" + xzqhbm + "' and " +
                    sql.substring(sql.indexOf("where") + "where".length());
            } else {
                sql = sql.substring(0, sql.indexOf("yj_yjsjb") + "yj_yjsjb".length()) +
                    " where yzqhbm like '" + xzqhbm + "'" +
                    sql.substring(sql.indexOf("yj_yjsjb") + "yj_yjsjb".length());
            }
            log.info("当前用户id:{},所在区县：{},修改后的sql：{}", userId, xzqhbm, sql);
            //通过反射修改sql语句
            Field field = boundSql.getClass().getDeclaredField("sql");
            field.setAccessible(true);
            field.set(boundSql, sql);
            return invocation.proceed();
        }
        //执行结果
        return invocation.proceed();
    }
}
